package com.sunday.pinxinghui.model.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Address;
import com.sunday.pinxinghui.entity.CartConfirm;
import com.sunday.pinxinghui.entity.CartItem;
import com.sunday.pinxinghui.entity.OrderCreate;
import com.sunday.pinxinghui.entity.ServicePlace;
import com.sunday.pinxinghui.model.mine.AddAddressActivity;
import com.sunday.pinxinghui.model.mine.AddressListActivity;
import com.sunday.pinxinghui.model.mine.SelectVoucherListActivity;
import com.sunday.pinxinghui.model.mine.ServicePlaceListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.R.id.address_layout;

/**
 * Created by 刘涛 on 2017/8/18.
 */

public class OrderConfirmActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_mobile)
    TextView userMobile;
    @Bind(R.id.linearlayout)
    LinearLayout linearlayout;
    @Bind(R.id.user_addr)
    TextView userAddr;
    @Bind(R.id.select_img)
    ImageView selectImg;
    @Bind(address_layout)
    RelativeLayout addressLayout;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.coupon_num)
    TextView couponNum;
    @Bind(R.id.select_coupon)
    LinearLayout selectCoupon;
    @Bind(R.id.get_score)
    TextView canGetScore;

    @Bind(R.id.txt_select_service_place)
    TextView selectServicePlace;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.phone_number)
    TextView phoneNumber;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.distance)
    TextView distance;
    @Bind(R.id.send_method)
    TextView sendMethod;
    @Bind(R.id.service_layout_item)
    RelativeLayout serviceLayoutItem;
    @Bind(R.id.txt_express_title)
    TextView txtExpressTitle;
    @Bind(R.id.express_money)
    TextView expressMoney;
    @Bind(R.id.edit_remark)
    EditText editRemark;
    @Bind(R.id.score_num)
    TextView scoreNum;
    @Bind(R.id.select_use_score)
    CheckBox selectUseScore;
    @Bind(R.id.total_money_bottom)
    TextView totalMoneyBottom;
    @Bind(R.id.product_num)
    TextView productNum;
    @Bind(R.id.confirm_pay)
    Button confirmPay;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.score_layout)
    LinearLayout scoreLayout;
    @Bind(R.id.ll_add_addr)
    LinearLayout llAddAddr;
    @Bind(R.id.ll_express_fee)
    LinearLayout ll_express_fee;
    @Bind(R.id.pro_money)
    TextView proMoney;


    private CartConfirm cartConfirm;
    private long memberId;
    private Address revievedAddr;
    private String catIds;
    private boolean isFromBuyNow;
    private Integer normalId = null;
    private long productId;
    private int isTotalFreePost;//是否包邮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirm);
        ButterKnife.bind(this);
        titleView.setText("确认订单");
        cartConfirm = (CartConfirm) getIntent().getSerializableExtra("orderConfirm");
        catIds = getIntent().getStringExtra("catIds");
        isFromBuyNow = getIntent().getBooleanExtra("isFromBuyNow", false);
        normalId = getIntent().getIntExtra("normalId", 0);
        memberId = BaseApplication.getInstance().getMember().getId();
        productId = getIntent().getLongExtra("productId", 0);
        titleView.setFocusable(true);
        titleView.setFocusableInTouchMode(true);
        titleView.requestFocus();
        initView();
    }

    private BigDecimal pointFee = BigDecimal.ZERO;//积分抵扣
    private Integer pledgeMethod;//1:积分抵扣

    private void initView() {
        serviceLayoutItem.setVisibility(View.GONE);
        if (cartConfirm == null) {
            return;
        }
        revievedAddr = cartConfirm.getReceiveAddress();
        setAddr(revievedAddr);
        isTotalFreePost = cartConfirm.getIsTotalFreePost();
        if (cartConfirm.getProductDetails() != null) {
            listView.setAdapter(new CommenAdapter<CartItem>(mContext, cartConfirm.getProductDetails(), R.layout.order_product_item) {
                @Override
                public void convert(ViewHolder helper, CartItem item, int position) {
                    ImageView productImage = helper.getView(R.id.product_image);
                    ImageView flagImg = helper.getView(R.id.flag_img);
                    if (!TextUtils.isEmpty(item.getProductImage())) {
                        Glide.with(mContext)
                                .load(item.getProductImage())
                                .error(R.mipmap.ic_default)
                                .into(productImage);
                    }
                    ((TextView) helper.getView(R.id.product_name)).setText(item.getProductName());
                    ((TextView) helper.getView(R.id.product_params)).setText(item.getNormal());
                    ((TextView) helper.getView(R.id.product_price)).setText(String.format("¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
                    ((TextView) helper.getView(R.id.product_num)).setText("X" + item.getNum());

                    switch (item.getType()) {
                        case 1:
                            //普通商品
                            flagImg.setVisibility(View.GONE);
                            break;
                        case 2:
                            //秒杀产品
                            flagImg.setVisibility(View.VISIBLE);
                            flagImg.setImageResource(R.mipmap.miaosha);
                            break;
                        case 3:
                            //限时购商品
                            flagImg.setVisibility(View.VISIBLE);
                            flagImg.setImageResource(R.mipmap.qianggou);
                            break;
                    }
                }
            });
        }
        canGetScore.setText(cartConfirm.getCanGetScore() == null ? "" : cartConfirm.getCanGetScore() + "积分");
        if (cartConfirm.getScore() > 0) {
            scoreNum.setVisibility(View.VISIBLE);
            scoreNum.append(SpannalbeStringUtils.setTextColor(String.format("余%d积分可抵扣", cartConfirm.getScore()), ContextCompat
                    .getColor(mContext, R.color._333)));
            scoreNum.append(SpannalbeStringUtils.setTextColor(String.format("¥%s", cartConfirm.getScoreAmount().setScale(2, RoundingMode.HALF_UP)), ContextCompat
                    .getColor(mContext, R.color.main_color)));
        } else {
            scoreLayout.setVisibility(View.GONE);
        }

        selectUseScore.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    pledgeMethod = 1;
                    pointFee = cartConfirm.getScoreAmount();
                } else {
                    pledgeMethod = null;
                    pointFee = BigDecimal.ZERO;
                }
                reCountTotalMoney();
            }
        });

        totalMoneyBottom.setText(String.format("总金额：¥%s", cartConfirm.getTotalFee().setScale(2, RoundingMode.HALF_UP)));
        productNum.setText(SpannalbeStringUtils.setTextColor("(共", ContextCompat.getColor(mContext, R.color._666)));
        productNum.append(SpannalbeStringUtils.setTextColor(cartConfirm.getProductDetails().size() + "", ContextCompat.getColor(mContext, R.color.main_color)));
        productNum.append(SpannalbeStringUtils.setTextColor("件商品)", ContextCompat.getColor(mContext, R.color._666)));
        proMoney.setText(String.format("¥%s", cartConfirm.getTotalFee().setScale(2, RoundingMode.HALF_UP)));
        ll_express_fee.setVisibility(View.GONE);

    }

    private void setAddr(Address addr) {
        if (addr == null) {
            addressLayout.setVisibility(View.GONE);
            llAddAddr.setVisibility(View.VISIBLE);
            userName.setText("暂无收货地址");
            userMobile.setText("");
            userAddr.setText("请添加收货地址");
        } else {
            addressLayout.setVisibility(View.VISIBLE);
            llAddAddr.setVisibility(View.GONE);
            userName.setText("收货人：" + addr.getName());
            userMobile.setText(addr.getMobile());
            userAddr.setText("地址：" + addr.getProvinceName() + addr.getCityName() + addr.getDistrictName() +
                    addr.getStreetName() + addr.getAddress());
        }
    }

    private final static int REQUEST_ADDR = 0x1111;
    private final static int REQUEST_COUNPON = 0x1112;
    private final static int REQUEST_SERVICE_PLACE = 0x1113;

    @OnClick({R.id.select_coupon, R.id.address_layout, R.id.select_service_place, R.id.confirm_pay, R.id.ll_add_addr})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_coupon:
                intent = new Intent(mContext, SelectVoucherListActivity.class);
                intent.putExtra("money", cartConfirm.getTotalFee().doubleValue());
                startActivityForResult(intent, REQUEST_COUNPON);
                break;
            case R.id.address_layout:
                if (revievedAddr == null) {
                    intent = new Intent(mContext, AddAddressActivity.class);
                    intent.putExtra("isSelectMode", true);
                    startActivityForResult(intent, REQUEST_ADDR);
                } else {
                    intent = new Intent(mContext, AddressListActivity.class);
                    intent.putExtra("isSelectMode", true);
                    startActivityForResult(intent, REQUEST_ADDR);
                }
                break;
            case R.id.ll_add_addr:
                intent = new Intent(mContext, AddAddressActivity.class);
                intent.putExtra("isSelectMode", true);
                startActivityForResult(intent, REQUEST_ADDR);
                break;
            case R.id.select_service_place:
                if (revievedAddr == null) {
                    ToastUtils.showToast(mContext, "请先选择收货地址");
                    return;
                }
                intent = new Intent(mContext, ServicePlaceListActivity.class);
                intent.putExtra("addressId", revievedAddr.getId());
                intent.putExtra("isFromSelect", true);
                startActivityForResult(intent, REQUEST_SERVICE_PLACE);
                break;
            case R.id.confirm_pay:
                if (revievedAddr == null) {
                    ToastUtils.showToast(mContext, "请选择收货地址");
                    return;
                }
                if (!isSelectServicePlace) {
                    ToastUtils.showToast(mContext, "请在下方选择配送点和取货方式");
                    return;
                }
                String memos = editRemark.getText().toString().trim();
                showLoadingDialog(0);
                Call<ResultDO<OrderCreate>> call = null;
                if (!isFromBuyNow) {
                    call = ApiClient.getApiAdapter().carToOrder(catIds, memberId, revievedAddr.getId(),
                            pledgeMethod, memos, servicePlace != null ? servicePlace.getId() : null, isSelf == 1 ? isSelf : null, voucherId);
                    call.enqueue(new Callback<ResultDO<OrderCreate>>() {
                        @Override
                        public void onResponse(Call<ResultDO<OrderCreate>> call, Response<ResultDO<OrderCreate>> response) {
                            dissMissDialog();
                            if (isFinish || response.body() == null) {
                                return;
                            }
                            if (response.body().getCode() == 0) {
                                intent = new Intent(mContext, OrderPayActivity.class);
                                intent.putExtra("orderId", response.body().getResult().getOrderId());
                                intent.putExtra("totalMoney", String.format("%s", response.body().getResult().getTotalFee().setScale(2, RoundingMode.HALF_UP)));
                                intent.putExtra("recieveName", servicePlace != null ? servicePlace.getName() + servicePlace.getMobile() :
                                        revievedAddr.getName() + revievedAddr.getMobile());
                                intent.putExtra("recieveAddr", servicePlace != null ? servicePlace.getAddress() : revievedAddr.getAddress());
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtils.showToast(mContext, response.body().getMessage());
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultDO<OrderCreate>> call, Throwable t) {
                            dissMissDialog();
                            ToastUtils.showToast(mContext, R.string.network_error);
                        }
                    });
                } else {
                    call = ApiClient.getApiAdapter().buyNowCreateOrder(productId, cartConfirm.getTotalNum(), normalId, memberId, revievedAddr.getId(),
                            pledgeMethod, memos, servicePlace != null ? servicePlace.getId() : null, isSelf == 1 ? isSelf : null, voucherId);
                    call.enqueue(new Callback<ResultDO<OrderCreate>>() {
                        @Override
                        public void onResponse(Call<ResultDO<OrderCreate>> call, Response<ResultDO<OrderCreate>> response) {
                            dissMissDialog();
                            if (isFinish || response.body() == null) {
                                return;
                            }
                            if (response.body().getCode() == 0) {
                                intent = new Intent(mContext, OrderPayActivity.class);
                                intent.putExtra("orderId", response.body().getResult().getOrderId());
                                intent.putExtra("totalMoney", String.format("%s", response.body().getResult().getTotalFee().setScale(2, RoundingMode.HALF_UP)));
                                intent.putExtra("recieveName", servicePlace != null ? servicePlace.getName() + servicePlace.getMobile() :
                                        revievedAddr.getName() + revievedAddr.getMobile());
                                intent.putExtra("recieveAddr", servicePlace != null ? servicePlace.getAddress() : revievedAddr.getAddress());
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtils.showToast(mContext, response.body().getMessage());
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultDO<OrderCreate>> call, Throwable t) {
                            dissMissDialog();
                            ToastUtils.showToast(mContext, R.string.network_error);
                        }
                    });
                }
                break;


        }
    }

    private double couponMoney = 0;
    private BigDecimal expressFee = BigDecimal.ZERO;
    private Integer voucherId = null;
    private ServicePlace servicePlace = null;
    private int isSelf;//是否自提 0：否 1：是
    private boolean isSelectServicePlace;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADDR:
                revievedAddr = (Address) data.getSerializableExtra("address");
                setAddr(revievedAddr);
                initSelectServicePlace();
                break;
            case REQUEST_COUNPON:
                voucherId = data.getIntExtra("id", 0);
                couponMoney = data.getDoubleExtra("money", 0);
                reCountTotalMoney();
                break;
            case REQUEST_SERVICE_PLACE:
                selectServicePlace.setText("");
                servicePlace = (ServicePlace) data.getSerializableExtra("servicePlace");
                isSelf = data.getIntExtra("isSelf", 0);
                isSelectServicePlace = true;
                updateView();
                break;

        }
    }

    private void initSelectServicePlace() {
        servicePlace = null;
        isSelectServicePlace = false;
        selectServicePlace.setText("未选择");
        serviceLayoutItem.setVisibility(View.GONE);
        ll_express_fee.setVisibility(View.GONE);
        expressFee = BigDecimal.ZERO;
        reCountTotalMoney();
    }


    private void updateView() {
        serviceLayoutItem.setVisibility(View.VISIBLE);
        ll_express_fee.setVisibility(isSelectServicePlace ? View.VISIBLE : View.GONE);
        if (servicePlace == null) {
            address.setText(mContext.getString(R.string.default_send_method));
            address.setVisibility(View.VISIBLE);
            phoneNumber.setVisibility(View.GONE);
            name.setVisibility(View.GONE);
            distance.setVisibility(View.GONE);
            sendMethod.setText("快递");
//            if (isFreePost==1){
//                expressFee = cartConfirm.getSpecialExpressFee();
//            }else {
//                if (ex)
//            }
            expressFee = cartConfirm.getExpressFee().add(cartConfirm.getSpecialExpressFee());
            //expressMoney.setText("¥" + cartConfirm.getExpressFee().add(cartConfirm.getSpecialExpressFee()).setScale(2, RoundingMode.HALF_UP));
            expressMoney.setText("¥" +expressFee.setScale(2,RoundingMode.HALF_UP));
            txtExpressTitle.setText("运费");

        } else {
            name.setText(servicePlace.getName());
            address.setVisibility(View.VISIBLE);
            name.setVisibility(View.VISIBLE);
            distance.setVisibility(View.VISIBLE);
            name.setText(servicePlace.getName());
            phoneNumber.setText(servicePlace.getMobile());
            address.setText(servicePlace.getAddress());
            distance.setText(servicePlace.getDistance() + "km");
            sendMethod.setText(isSelf == 0 ? "品行专送" : "自提");
            txtExpressTitle.setText(isSelf == 0 ? "配送费" : "服务费");
            if (isTotalFreePost == 1) {
                //包邮
                expressFee = BigDecimal.ZERO;
                expressMoney.setText("¥0.00");
            } else {
                //不包邮 要算专送费用和自提费用
                expressFee = isSelf == 0 ? cartConfirm.getServiceFee() : cartConfirm.getSinceFee();
                expressMoney.setText("¥" + expressFee.setScale(2, RoundingMode.HALF_UP));
            }
//            expressMoney.setText(isSelf == 0 ? "¥" + cartConfirm.getServiceFee().setScale(2, RoundingMode.HALF_UP) :
//                    "¥" + cartConfirm.getSinceFee().setScale(2, RoundingMode.HALF_UP));
//            expressFee = isSelf == 0 ? cartConfirm.getServiceFee() : cartConfirm.getSinceFee();
        }

        reCountTotalMoney();
    }

    private void reCountTotalMoney() {

        BigDecimal coupMoney = new BigDecimal(Double.toString(couponMoney));
        if (coupMoney.compareTo(BigDecimal.ZERO) > 0) {
            couponNum.setText(String.format("¥%s", coupMoney.setScale(2, RoundingMode.HALF_UP)));
        }

        BigDecimal allMoney = cartConfirm.getTotalFee().subtract(coupMoney).add(expressFee).subtract(pointFee);
        totalMoneyBottom.setText(String.format("实付金额：¥%s", allMoney.setScale(2, RoundingMode.HALF_UP)));

    }

}
